<script setup>
import {ref,onMounted} from 'vue'
import { getAllClazzApi,getAllStudentApi,addStudentApi,getStudentById ,updateStudent,deleteStudentByIdApi,violationApi} from '@/api/student.js'
import { ElMessage , ElMessageBox } from 'element-plus';


/* 关联查询表单 */
const searchStudent=ref({
  name:'',
  degree:'',
  clazzId:''
})
/* 关联学生表格 */
const studentList=ref([])
/* 页码 */
const page=ref(1)
/* 每页展示条数 */
const pageSize=ref(10)
/* 数据总数 */
const stuTotal=ref(0)
/* 表单实例 */
const stuFormRef=ref()
/* 表单显示/隐藏 */
const dialogVisible=ref(false)
/* 表单标题 */
const dialogTitle=ref('')
/* 学历 */
const degreeList=ref([
  {name:'初中',value:1},
  {name:'高中',value:2},
  {name:'大专',value:3},
  {name:'本科',value:4},
  {name:'硕士',value:5},
  {name:'博士',value:6}
]
)
/* 性别维护 */
const genderList=ref([{key:'男',value:'1'},{key:'女',value:'2'}])
const student=ref({
  id:'',
  name:'',
  no:'',
  gender:'',
  phone:'',
  idCard:'',
  isCollege:'',
  address:'',
  degree:'',
  graduationDate:'',
  clazzId:'',
  violationCount:'',
  violationScore:''
})
const clazzs=ref([])
/* 班级列表 */
const clazzList=ref([])
/* 查询所有班级 */
const getAllClazz=async()=>{
 const result=await getAllClazzApi()
  if(result.code){
    clazzs.value=result.data
    if(clazzs.value && clazzs.value.length){
      clazzs.value.forEach(clazz => {
        clazzList.value.push({key:clazz.name,value:clazz.id})
      })
    }
  }
}

const search=async()=>{
  const result=await getAllStudentApi(
    searchStudent.value.name,
    searchStudent.value.degree,
    searchStudent.value.clazzId,
    page.value,
    pageSize.value
  )
  if(result.code){
    stuTotal.value=result.data.total
    studentList.value=result.data.rows
  }
}
const clear=()=>{
  searchStudent.value={
    name:'',
    degree:'',
    clazzId:''
  }
  search()
}
/* 钩子函数 */
onMounted(()=>{
  getAllClazz()
  search()
})
const handleSizeChange=()=>{
  search();
}
const handleCurrentChange=()=>{
  search();
}
/* 新增学生 */
const addStu=async()=>{
  dialogVisible.value=true
  dialogTitle.value='添加学员'
  student.value={
    name:'',
    no:'',
    gender:'',
    phone:'',
    idCard:'',
    isCollege:'',
    address:'',
    degree:'',
    graduationDate:'',
    clazzId:''
  }
  stuFormRef.value.resetFields()
} 
/* 保存学生 */
const saveStudent=async()=>{
  if (!stuFormRef.value) return
     await stuFormRef.value.validate(async (valid, fields) => {
        if (valid) {
          /* 校验成功 */
          let result;
          if(student.value.id){
            result=await updateStudent(student.value)
          }else{
            result=await addStudentApi(student.value)
          }
          if(result.code){
            ElMessage.success('添加成功')
            dialogVisible.value=false
            search()
          }else{
            ElMessage.error(result.msg)
          }
       } else {
      /* 校验失败 */
          ElMessage.error('校验失败,请重新输入')
          stuFormRef.value.resetFields()
    }    
  })
}
/* 数据校验规则 */
const rules = ref({
  name: [
    { required: true, message: '姓名不能为空', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度为2-10位', trigger: 'blur' },
  ],
  no: [
    { pattern: /^[a-zA-Z0-9]{10}$/, message: '学号长度为10位', trigger: 'blur' },
    { required: true, message: '学号不能为空', trigger: 'blur' },
  ],
  gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的电话号码', trigger: 'blur' },
    { required: true, message: '电话号码不能为空', trigger: 'blur' },   
  ],
  idCard: [
    { pattern: /^\d{18}$/, message: '请输入正确的电话号码', trigger: 'blur' },
    { required: true, message: '身份证号不能为空', trigger: 'blur' },   
  ],
  isCollege: [{ required: true, message: '请选择是否院校学生', trigger: 'blur' }],
  address: [{  min: 0, max: 100, message: '地址长度为0-100', trigger: 'blur'  }]
 })
 const editStudent=async (id)=>{
  const result=await getStudentById(id)
  if(result.code){
    dialogVisible.value=true
    dialogTitle.value='修改员工'
    student.value=result.data
  }else{
    ElMessage.error(result.msg)
    console.console.log('dev分支修改了文件');
    
  }
 }
/*  删除学生 */
 const deleteStudent=(id)=>{
  ElMessageBox.confirm(
    '确认删除','提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ) .then(async() => {
      const result=await deleteStudentByIdApi(id)
      if(result.code){
        search()
        ElMessage.success('删除成功')
      }
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
 }
 const ids=ref([])
 /* 批量删除 */
 const handleSelectionChange = (val) => {
  ids.value=val.map(item=>item.id)
}
const deleteStudents=()=>{
  ElMessageBox.confirm(
    '确认删除','提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ) .then(async() => {
      const result=await deleteStudentByIdApi(ids.value)
      if(result.code){
        search()
        ElMessage.success('删除成功')
      }
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}
const violationDialogFormVisible=ref(false)
const violationOperation=(id)=>{
  violationDialogFormVisible.value=true
  student.value.violationScore=''
  student.value.id=id
}
const violationFormConfirm=async()=>{
  const result=await violationApi(student.value.id,student.value.violationScore)
  if(result.code){
    ElMessage.success('修改成功')
    search()
    violationDialogFormVisible.value=false
  }else{
    ElMessage.error('修改失败')
  }
}
</script>

<template>
  <h1>学员管理</h1>
  <div class="btn"> 
    <el-button type="primary" @click="addStu">+ 新增员工</el-button>
    <el-button type="danger" @click="deleteStudents">- 批量删除</el-button>
  </div>
  <div class="title">
    <el-form :inline="true" :model="searchStudent" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="searchStudent.name" placeholder="请输入学生姓名" clearable />
      </el-form-item>
      <el-form-item label="最高学历">
        <el-select
          v-model="searchStudent.degree"
          placeholder="请选择"
          clearable
        >
          <el-option v-for="(degree,index) in degreeList"  :label="degree.name" :value="degree.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="所属班级">
        <el-select
          v-model="searchStudent.degree"
          placeholder="请选择"
          clearable
        >
          <el-option v-for="(clazz,index) in clazzList"  :label="clazz.key" :value="clazz.value"/>
        </el-select>
      </el-form-item>
  
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>

  <el-table :data="studentList" border style="width: 100%" align="center" @selection-change="handleSelectionChange" >
    <el-table-column type="selection" width="55"/>
    <el-table-column prop="name" label="姓名" width="150" align="center" />
    <el-table-column prop="no" label="学号" width="150" align="center" />
    <el-table-column prop="clazzName" label="班级" width="250" align="center" />
    <el-table-column prop="gender" label="性别" width="100" align="center">
      <template #default="scope">
      {{ scope.row.gender==1 ? '男':'女' }}
      </template>
    </el-table-column>
    <el-table-column prop="phone" label="手机号" width="150" align="center" />
    <el-table-column prop="degree" label="最高学历" width="100" align="center">
      <template #default="scope">
        <span v-if="scope.row.degree==1">初中</span>
        <span v-else-if="scope.row.degree==2">高中</span>
        <span v-else-if="scope.row.degree==3">大专</span>
        <span v-else-if="scope.row.degree==4">本科</span>
        <span v-else-if="scope.row.degree==5">硕士</span>
        <span v-else-if="scope.row.degree==6">博士</span>
        <span v-else>其他</span>
      </template>
    </el-table-column>
    <el-table-column prop="violationCount" label="违纪次数" width="100" align="center"/>
    <el-table-column prop="violationScore" label="违纪扣分" width="100" align="center"/>
    <el-table-column prop="updateTime" label="最后操作时间" width="200" align="center"/>
    <el-table-column  label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" @click="editStudent(scope.row.id)" size="small">编辑</el-button>
        <el-button type="warning" @click="violationOperation(scope.row.id)" size="small" >违纪</el-button>
        <el-button type="danger" size="small" @click="deleteStudent(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="limit">
     <el-pagination
       v-model:current-page="page"
       v-model:page-size="pageSize"
       :page-sizes="[5,10, 20, 30, 40,50]"
       layout="total, sizes, prev, pager, next, jumper"
       :total="stuTotal"
       @size-change="handleSizeChange"
       @current-change="handleCurrentChange"
     />
    </div>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" align-center="true" center >
      <el-form ref="stuFormRef" :model="student" label-width="80px" size="large" :rules="rules"><!-- :rules="" -->
        <!-- 基本信息 -->
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="student.name" placeholder="请输入姓名"></el-input>
            </el-form-item >
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="学号" prop="no">
              <el-input v-model="student.no" placeholder="请输入学号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="student.gender" placeholder="请选择" style="width: 100%;">
                <el-option  v-for="(gender, index) in genderList"  :label="gender.key" :value="gender.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone" >
              <el-input v-model="student.phone" placeholder="请输入手机号"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard" >
              <el-input v-model="student.idCard" placeholder="请输入身份证号"/>
            </el-form-item>
          </el-col>

          <el-col :span="12" prop="isCollege">
            <el-form-item label="是否院校"  >
              <el-select v-model="student.isCollege" placeholder="请选择">
                <el-option label="是" value="1" />
                 <el-option label="否" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系地址" prop="address">
              <el-input v-model="student.address" placeholder="请输入联系地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最高学历">
              <el-select v-model="student.degree" placeholder="请选择" style="width: 100%;">
                <el-option  v-for="(degree, index) in degreeList"  :label="degree.name" :value="degree.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="毕业时间" style="width: 100%;">
              <el-date-picker v-model="student.graduationDate" type="date" placeholder="请选择毕业时间" value-format="YYYY-MM-DD"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属班级">
              <el-select v-model="student.clazzId" placeholder="请选择" style="width: 100%;">
                <el-option  v-for="(clazz, index) in clazzList"  :label="clazz.key" :value="clazz.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer" >
          <el-button type="info" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveStudent">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 违纪处理对话框 -->

    <el-dialog v-model="violationDialogFormVisible" title="提示" width="500"  center>
    <el-form :model="student" label-position="top">
      <el-form-item label="请输入违纪扣分" label-width="500">
        <el-input v-model="student.violationScore"  />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="violationDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="violationFormConfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.title{
  margin: 20px 0;
}
.limit{
  margin-top: 10px;
}
.btn{
  margin: 20px 0;
}

</style>